package com.android.ailaoshan.sound;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.ailaoshan.R;
import com.android.ailaoshan.tools.BaseAdapter;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class SoundAdapter extends BaseAdapter<SoundAdapter.ViewHolder> {

    private final String SOUND_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"AiLaoShan"+ File.separator + "Sound" + File.separator;
    private SimpleDateFormat formatter = new SimpleDateFormat("mm:ss", Locale.getDefault());

    private List<String> mDataList;

    SoundAdapter(Context context) {
        super(context);
    }

    public void notifyDataSetChanged(List<String> dataList) {
        this.mDataList = dataList;
        super.notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    @NonNull
    @Override
    public SoundAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new SoundAdapter.ViewHolder(getInflater().inflate(R.layout.sound, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String filePath = SOUND_PATH + mDataList.get(position);
        File file = new File(filePath);
        if(file.exists()){
            holder.imageView.setImageResource(R.drawable.sound_picture);
            MediaPlayer mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(filePath);
                mediaPlayer.prepare();
                long timeLength = mediaPlayer.getDuration();

                holder.textView.setText(formatter.format(timeLength));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;
        ViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.sound_picture);
            textView = itemView.findViewById(R.id.sound_length_txt);
        }
    }
}
